import axios from 'axios';

const API_URL = 'http://172.16.103.206:8081/api';

export interface User {
    id: string;
    username: string;
    email: string;
    role: 'student' | 'teacher' | 'admin';
    createdAt: string;
}

export interface UpdateUserData {
    username?: string;
    email?: string;
}

export interface UpdatePasswordData {
    currentPassword: string;
    newPassword: string;
}

// 获取当前用户信息
export const getCurrentUser = async (): Promise<User> => {
    const response = await axios.get(`${API_URL}/users/me`, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    });
    return response.data;
};

// 更新用户信息
export const updateUser = async (data: UpdateUserData): Promise<User> => {
    const response = await axios.put(`${API_URL}/users/me`, data, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    });
    return response.data;
};

// 修改密码
export const updatePassword = async (data: UpdatePasswordData): Promise<void> => {
    await axios.put(`${API_URL}/users/me/password`, data, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    });
};

// 获取用户列表（仅管理员）
export const getUsers = async (): Promise<User[]> => {
    const response = await axios.get(`${API_URL}/users`, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    });
    return response.data;
};

// 更新用户角色（仅管理员）
export const updateUserRole = async (userId: string, role: User['role']): Promise<User> => {
    const response = await axios.put(`${API_URL}/users/${userId}/role`, { role }, {
        headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
        }
    });
    return response.data;
}; 